import { getValidDate } from '@/dataTransfer/coupon';
import { debounce } from '@/utils/helper.js';
import { useShowLoading } from '@/utils/hooks/useShowLoading';
import { ScrollView, View } from '@tarojs/components';
import { useRouter } from '@tarojs/taro';
import classNames from 'classnames';
import React, { useCallback, useEffect, useState } from 'react';
import { connect } from 'react-redux';
import { dateFormat } from '../../utils/time';
import GiftCardBackground from '../giftCardBackground';
import './index.scss';
import ListEnd from './listEnd';

const TransType = {
  // 充值
  save: 1,
  // 消费
  consume: 2,
  // 退货
  refund: 3,
};

const TransTypeName = {
  [TransType.save]: '充值',
  [TransType.consume]: '消费',
  [TransType.refund]: '退货',
};

function transform(list) {
  const temp = list
    ?.map((item) => {
      const date = getValidDate(item.transactionDate);
      return {
        ...item,
        date,
        dateStr: dateFormat(date, 'MM-dd hh:mm'),
        monthStr: dateFormat(date, 'yyyy年MM月'),
      };
    })
    ?.reduce((r, item) => {
      if (!r[item.monthStr]) {
        r[item.monthStr] = [];
      }

      r[item.monthStr].push(item);
      return r;
    }, {});

  return Object.keys(temp ?? {}).map((key) => {
    return {
      monthStr: key,
      list: temp[key],
    };
  });
}

const Card = ({ detail }) => {
  const { cardNo, amount, backgroundContent, backgroundType } = detail ?? {};

  return (
    <View className="card-item">
      <GiftCardBackground className="card-pic" {...{ backgroundContent, backgroundType }} />

      <View className="card-info">
        <View className="gift-card-balance">
          <View className="balance-unit">¥</View>

          <View className="balance-number">{amount}</View>
        </View>

        <View className="card-no">券号：{cardNo}</View>
      </View>
    </View>
  );
};

const ConsumeItem = ({ monthStr, list }) => {
  return (
    <View className="consume-item">
      <View className="consume-month">{monthStr}</View>

      <View className="consume-record-list">
        {list?.map(({ id, dateStr, amount, transType }) => {
          return (
            <View key={id} className="consume-record">
              <View className="consume-record-top">
                <View className="mode">{TransTypeName[transType]}</View>
                <View
                  className={classNames('record', {
                    income: [TransType.save, TransType.refund].includes(transType),
                  })}
                >
                  {[TransType.save, TransType.refund].includes(transType) ? '+' : '-'}
                  {amount}
                </View>
              </View>

              <View className="date">{dateStr}</View>
            </View>
          );
        })}
      </View>
    </View>
  );
};

const ConsumeModes = {
  // 全部
  all: '',
  // 收入
  income: 1,
  // 支出
  outlay: 2,
};

const ConsumeList = [
  {
    label: '全部',
    mode: ConsumeModes.all,
  },
  {
    label: '收入',
    mode: ConsumeModes.income,
  },
  {
    label: '支出',
    mode: ConsumeModes.outlay,
  },
];

const GiftCardDetail = ({
  dispatch,
  loading,
  myGiftCard,
  myGiftCardTransactionList,
  myGiftCardTransactionFinished,
}) => {
  useShowLoading(loading, ['giftCard/getMyGiftCard', 'giftCard/fetchMyGiftCardTransactionList']);

  const router = useRouter();
  const { params = {} } = router;

  const [selectedMode, setSelectedMode] = useState(ConsumeModes.all);

  // 获取使用记录
  const getNextList = useCallback(() => {
    return dispatch({
      type: 'giftCard/fetchMyGiftCardTransactionList',
      payload: { pageSize: 10, cardId: params.id, type: selectedMode },
    });
  }, [params.id, selectedMode]);

  // 滚动获取
  const handleScrollToLower = debounce(() => {
    !myGiftCardTransactionFinished && myGiftCardTransactionList?.length > 0 && getNextList();
  }, 1200);

  // 获取我的提货券详情
  useEffect(() => {
    dispatch({
      type: 'giftCard/getMyGiftCard',
      payload: params.id,
    });
  }, [params.id]);

  // 获取使用记录
  useEffect(() => {
    getNextList();
  }, [getNextList]);

  const transactions = transform(myGiftCardTransactionList);

  return (
    <>
      <ScrollView
        className="giftCardDetail"
        enableFlex
        scrollY
        onScrollToLower={handleScrollToLower}
      >
        <Card className="card-item" detail={myGiftCard}></Card>

        <View className="consume-mode">
          {ConsumeList.map(({ label, mode }) => {
            return (
              <View
                key={mode}
                className="consume-mode-item-wrap"
                onClick={() => {
                  setSelectedMode(mode);
                }}
              >
                <View
                  className={classNames('consume-mode-item', {
                    'selected customePageStyle': selectedMode === mode,
                  })}
                >
                  {label}
                </View>
              </View>
            );
          })}
        </View>

        <View className="consume-list">
          {transactions?.map((item) => {
            return <ConsumeItem key={item.monthStr} {...item}></ConsumeItem>;
          })}
        </View>

        {myGiftCardTransactionFinished && myGiftCardTransactionList?.length > 8 && <ListEnd />}
      </ScrollView>
    </>
  );
};
export default connect(({ loading, giftCard }) => ({
  loading,
  myGiftCard: giftCard.myGiftCard,
  myGiftCardTransactionList: giftCard.myGiftCardTransactionList,
  myGiftCardTransactionFinished: giftCard.myGiftCardTransactionFinished,
}))(GiftCardDetail);
